package com.rongke.web.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.mapper.UserMapper;
import com.rongke.model.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户验证码登陆
 */
@Transactional
public class CodeRealm extends AuthorizingRealm {
	@Autowired
	private UserMapper userDao;

	/**
	 * 为当前登录的用户授予权限
	 */
	@Override
	public AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// String phone = (String)principals.getPrimaryPrincipal();
		// SimpleAuthorizationInfo authorizationInfo = new
		// SimpleAuthorizationInfo();
		// try{
		// }catch(Exception e){
		// e.printStackTrace();
		// }
		// return authorizationInfo;
		return new SimpleAuthorizationInfo();
	}

	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String phone = (String) token.getPrincipal();
		EntityWrapper<User> ew = new EntityWrapper<User>();
		ew.eq("phone", phone);
		List<User> list = userDao.selectList(ew);
		User user = null;
		if (list.size() > 0) {
			user = list.get(0);
			AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(
					user.getPhone(), "123", getName());
			return authcInfo;
		} else {
			return null;
		}
	}
}
